package utils;


import com.itextpdf.text.Document;
import com.itextpdf.text.Rectangle;
import com.itextpdf.text.pdf.*;
import constant.Constant;
import entry.*;

import javafx.scene.control.Alert;
import shape.Shape;

import java.io.File;
import java.io.FileOutputStream;
import java.util.*;

public class ItextUtil {

    public static void createByPaper(List<List<Shape>> lists, String outPath, Size size) {
        try {

            Rectangle cropBox = new Rectangle(size.getW() * Constant.pt, size.getH() * Constant.pt);
            Document document = new Document(cropBox);//新建一个文档并且设置页面大小

            FileOutputStream outputStream = new FileOutputStream(outPath);//新建一个pdf文档;
            PdfWriter writer = PdfWriter.getInstance(document, outputStream);//把新建的pdf 赋值给 document
            writer.setPdfVersion(PdfWriter.VERSION_1_5);
            document.open();//打开 document文档
            PdfContentByte cb = writer.getDirectContent();
            for (int i = 0; i < lists.size(); i++) {



                document.newPage();
                for (Shape shape : lists.get(i)) {
                    shape.draw(cb);
                    shape.draw(cb, writer);
                }
            }
            outputStream.flush();//关闭文件
            document.close();//关闭文件
            outputStream.close();//关闭文件
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    public static List<Position> getJXPositions(float a, float b, float c, float d) {
        List<Position> list = new ArrayList<Position>();
        list.add(new Position(a, b));
        list.add(new Position(c, d));
        return list;
    }

    public static void mergePdf(String inPath, String outPath, String pinbanfangshi, Info info) {
        try {
            if (new File(outPath).exists()) new File(outPath).delete();

            PdfReader reader = new PdfReader(inPath);
            Rectangle cropBox = reader.getCropBox(1);
            float pageWidth = cropBox.getWidth();
            float pageHeight = cropBox.getHeight();
            boolean isRotate = false;
            if (pageWidth < pageHeight) {
                pageWidth = cropBox.getHeight();
                pageHeight = cropBox.getWidth();
                isRotate = true;
            }
            int pageCount = reader.getNumberOfPages();
            Document document = new Document(new Rectangle(pageWidth, pageHeight));//新建一个文档并且设置页面大小
            FileOutputStream outputStream = new FileOutputStream(outPath);//新建一个pdf文档;

            PdfWriter writer = PdfWriter.getInstance(document, outputStream);//把新建的pdf 赋值给 document
            writer.setPdfVersion(PdfWriter.VERSION_1_5);
            document.open();//打开 document文档
            PdfContentByte cb = writer.getDirectContent();
            for (int i = 1; i <= pageCount; i++) {
                document.newPage();
                PdfImportedPage importedPage = writer.getImportedPage(reader, i);

                if (isRotate) {
                    if (pinbanfangshi.indexOf("骑马钉") != -1 || pinbanfangshi.indexOf("胶装") != -1) {
                        if (i % 2 == 1) {
                            cb.addTemplate(importedPage, 0, 1, -1, 0, importedPage.getHeight(), 0);
                        } else {
                            cb.addTemplate(importedPage, 0, -1, 1, 0, 0, importedPage.getWidth());
                        }
                    } else if (pinbanfangshi.indexOf("单面") != -1 || pinbanfangshi.indexOf("自翻") != -1) {
                        cb.addTemplate(importedPage, 0, 1, -1, 0, importedPage.getHeight(), 0);
                    } else if (pinbanfangshi.indexOf("双面") != -1) {
                        if (i % 2 == 1) {
                            cb.addTemplate(importedPage, 0, 1, -1, 0, importedPage.getHeight(), 0);
                        } else {
                            cb.addTemplate(importedPage, 0, -1, 1, 0, 0, importedPage.getWidth());
                        }
                    }
                } else {
                    cb.addTemplate(importedPage, 0, 0);
                }
                MyTime myTime = new MyTime();
                String content = myTime.getYear() + "-" + myTime.getMonth() + "-" + myTime.getDate() + " " + new File(outPath).getName() + "【" + i+"-" + pageCount + "】";
                if (Constant.is_cc) {
                    addText(cb, new float[]{100, 0, 0, 0}, "C", pageWidth / 2 / Constant.pt + 6, 0.2f, 0);
                }
                if (Constant.is_cm) {
                    addText(cb, new float[]{0, 100, 0, 0}, "M", pageWidth / 2 / Constant.pt + 6 + 3, 0.2f, 0);
                }
                if (Constant.is_cy) {
                    addText(cb, new float[]{0, 0, 100, 0}, "Y", pageWidth / 2 / Constant.pt + 6 + 3 * 2, 0.2f, 0);
                }
                if (Constant.is_ck) {

                    addText(cb, new float[]{0, 0, 0, 100}, "K", pageWidth / 2 / Constant.pt + 6 + 3 * 3, 0.2f, 0);
                }
                if (Constant.is_left_text) {
                    addText(cb, new float[]{100, 100, 100, 100}, content, 2.8f, Constant.jiao_xian_chang_du + 6, 90);
                }
                if (Constant.is_right_text) {
                    addText(cb, new float[]{100, 100, 100, 100}, content, pageWidth / Constant.pt - 2.8f, pageHeight / Constant.pt - Constant.jiao_xian_chang_du - 6, 270);
                }
                if (Constant.is_bottom_text) {
                    addText(cb, new float[]{100, 100, 100, 100}, content, Constant.jiao_xian_chang_du + 3 + 3, 0.2f, 0);
                }
                if (Constant.is_top_text) {
                    addText(cb, new float[]{10, 100, 100, 100}, content, Constant.jiao_xian_chang_du + 3 + 3, pageHeight / Constant.pt - 2.8f, 0);
                }
                List<String> pt_list = info.getPt_list();
                if (pt_list != null && pt_list.size() > 0) {
                    for (int p=0;p<pt_list.size();p++) {

                        addTextzs(cb,pt_list.get(p), pageWidth / 2 / Constant.pt + 6 + 3 * 4+20*p, 0.2f);
                    }
                }


            }

            outputStream.flush();//关闭文件
            document.close();//关闭文件
            outputStream.close();//关闭文件
            reader.close();
            new File(inPath).delete();
            closeReaderMap();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private static void addTextzs(PdfContentByte cb, String s, float x, float y) {
        if (null != s && !"".equals(s)&&s.indexOf(",")!=-1) {
            try {
                cb.beginText();
                float pt = 72f / 25.4f;

                String[] split = s.split(",");


                ExtendedColor baseColor = new CMYKColor(Float.valueOf(split[1]) / 100.f, Float.valueOf(split[2]) / 100.f, Float.valueOf(split[3])  / 100.f, Float.valueOf(split[4]) / 100.f);

                PdfSpotColor pdfSpotColor = new PdfSpotColor(split[0], baseColor);
                cb.setColorFill(pdfSpotColor, 100f);
                BaseFont baseFont = BaseFont.createFont(Constant.font_msyh, BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);

                cb.setFontAndSize(baseFont, 6);
                cb.showTextAligned(PdfContentByte.ALIGN_LEFT, split[0], x* pt, y * pt, 0);
                cb.endText();
                cb.fillStroke();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    public static void addText(PdfContentByte cb, float[] arr, String content, float xxx, float yyy, int rotate) {
        TextInfo textInfo = new TextInfo();
        textInfo.setColorArr(arr);
        textInfo.setContent(content);
        textInfo.setFontName(Constant.font_msyh);
        textInfo.setFontSize(6);
        textInfo.setRotate(rotate);
        textInfo.setX(xxx);
        textInfo.setY(yyy);
        if (null != textInfo.getContent()) {
            try {
                float[] colorArr = textInfo.getColorArr();
                float pt = 72f / 25.4f;
                ExtendedColor baseColor = new CMYKColor(colorArr[0] / 100.f, colorArr[1] / 100.f, colorArr[2] / 100.f, colorArr[3] / 100.f);
                if (colorArr[0] == 100 && colorArr[1] == 100 && colorArr[2] == 100 && colorArr[3] == 100) {
                    PdfSpotColor pdfSpotColor = new PdfSpotColor("All", baseColor);
                    cb.setColorFill(pdfSpotColor, 100f);
                } else {
                    cb.setColorFill(baseColor);
                }

                BaseFont baseFont = BaseFont.createFont(textInfo.getFontName(), BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
                cb.beginText();
                cb.setFontAndSize(baseFont, textInfo.getFontSize());
                cb.showTextAligned(PdfContentByte.ALIGN_LEFT, textInfo.getContent(), textInfo.getX() * pt, textInfo.getY() * pt, textInfo.getRotate());
                cb.endText();
                cb.fillStroke();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    public static void addText(PdfContentByte cb, TextInfo textInfo) {
        if (null != textInfo.getContent()) {
            try {
                float[] colorArr = textInfo.getColorArr();
                float pt = 72f / 25.4f;
                ExtendedColor baseColor = new CMYKColor(colorArr[0] / 100.f, colorArr[1] / 100.f, colorArr[2] / 100.f, colorArr[3] / 100.f);
                cb.setColorFill(baseColor);
                BaseFont baseFont = BaseFont.createFont(textInfo.getFontName(), BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
                cb.beginText();
                cb.setFontAndSize(baseFont, textInfo.getFontSize());
                cb.showTextAligned(PdfContentByte.ALIGN_LEFT, textInfo.getContent(), textInfo.getX() * pt, textInfo.getY() * pt, textInfo.getRotate());
                cb.endText();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    public static void closeReaderMap() {
        for (Map.Entry<Integer, PdfReader> entry : Constant.pdfReaderMap.entrySet()) {
            if (entry.getValue() != null) {
                entry.getValue().close();
            }

        }
    }

    /**
     * 判断使用哪个 页面来拼版  在16P页面中调一个
     * https://blog.csdn.net/jialan75/article/details/115834887?spm=1001.2014.3001.5501
     *
     * @param c    当前列数
     * @param r    当前行数
     * @param col  最大列数
     * @param row  最大行数
     * @param flag true=正面 false=反面
     * @return
     */
    public static int getIndex(int c, int r, int col, int row, boolean flag, int rotate) {

        int index = 0;
        c++;
        r++;
        //row=1 col=1
        if (row == 1 && col == 1) {
            index = 16;
        }
//        row=1 col=2
        if (row == 1 && col == 2) {
            if (c == 1) {
                index = 10;
            } else {
                index = 12;
            }
        }
//        row=1 col>=3
        if (row == 1 && col >= 3) {
            if (c == 1) {
                index = 10;
            } else if (c == col) {
                index = 12;
            } else {
                index = 11;
            }
        }
//        row=2 col=1
        if (row == 2 && col == 1) {
            if (r == 1) {
                index = 15;
            } else {
                index = 13;
            }
        }
//        row=2 col=2
        if (row == 2 && col == 2) {
            //1,1
            if (r == 1 && c == 1) {
                index = 1;
            } else if (r == 1 && c == 2) {
                index = 7;
            } else if (r == 2 && c == 1) {
                index = 3;
            } else {
                index = 9;
            }
        }
//        row=2 col>=3
        if (row == 2 && col >= 3) {
            if (r == 1) {
                if (c == 1) {
                    index = 1;
                } else if (c == col) {
                    index = 7;
                } else {
                    index = 4;
                }
            } else {
                if (c == 1) {
                    index = 3;
                } else if (c == col) {
                    index = 9;
                } else {
                    index = 6;
                }
            }
        }
//        row=3 col=1
        if (row >= 3 && col == 1) {
            if (r == 1) {
                index = 15;
            } else if (r == row) {
                index = 13;
            } else {
                index = 14;
            }
        }
//        row=3 col=2
        if (row >= 3 && col == 2) {
            if (c == 1) {
                if (r == 1) {
                    index = 1;
                } else if (r == row) {
                    index = 3;
                } else {
                    index = 2;
                }
            } else {
                if (r == 1) {
                    index = 7;
                } else if (r == row) {
                    index = 9;
                } else {
                    index = 8;
                }
            }
        }
//        row>=3 col>=3
        if (row >= 3 && col >= 3) {
            if (r == 1) {
                if (c == 1) {
                    //1,1
                    index = 1;
                } else if (c == col) {
                    //1,3
                    index = 7;
                } else {
                    index = 4;
                }
            } else if (r == row) {
                if (c == 1) {
                    index = 3;
                } else if (c == col) {
                    index = 9;
                } else {
                    index = 6;
                }
            } else {
                if (c == 1) {
                    index = 2;
                } else if (c == col) {
                    index = 8;
                } else {
                    index = 5;
                }
            }
        }
        //如果是背面
        if (!flag) {
            Map<Integer, Integer> map = new HashMap<Integer, Integer>();
            map.put(1, 7);
            map.put(2, 8);
            map.put(3, 9);
            map.put(7, 1);
            map.put(8, 2);
            map.put(9, 3);
            map.put(10, 12);
            map.put(12, 10);
            Integer value = map.get(index);
            if (value != null) index = value;
        }


        if (!Constant.pdfReaderMap.containsKey(index)) {
            try {
                Constant.pdfReaderMap.put(index, new PdfReader(Constant.singlePath));
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return index;
    }

    public static void alert(String content, String titile) {
        Alert alert = new Alert(Alert.AlertType.ERROR);
        alert.setTitle(titile);
        alert.setContentText(content);
        alert.show();
    }
    public static void alertInfo(String content, String titile) {
        Alert alert = new Alert(Alert.AlertType.INFORMATION);
        alert.setTitle(titile);
        alert.setContentText(content);
        alert.show();
    }
}
